import socket
import StringIO
import telnetlib

class TelnetError(Exception):
   pass

class telnet(object):
   def __init__(self, Host, Port = 23):
      self._err = TelnetError()
      self._host = None
      self._port = 0
      self._str = StringIO.StringIO()
      self._tty = None

      if Host:
         self._host = Host
      else:
         self._error("No Host defined to login using telnet!")

      if Port:
         try:
            self._port = int(Port)
         except ValueError, message:
            self._error(message)

      try:
         self._telnet = telnetlib.Telnet(self._host, self._port)
      except socket.error, (errno, message):
         self._error(message)

   def _error(self, Message):
      if Message:
         self.Close()
         raise TelnetError, Message

   def Close(self):
      if self._telnet:
         self._telnet.close()

      if self._str:
         self._str.close()

   def Authenticate(self, Username, Password):
      if self._telnet:
         self._telnet.read_until("Username: ")
         try:
            self._telnet.write("%s\n" %Username.strip())
         except TypeError, message:
            self._telnet.write(("%s\n" %Username.strip()).encode('latin-1'))

         if Password:
            self._telnet.read_until("Password: ")
            try:
               self._telnet.write("%s\n" %Password.strip())
            except TypeError, message:
               self._telnet.write(("%s\n" %Password.strip()).encode('latin-1'))

   def SendFile(self, File):
      if File:
         fh = None
         try:
            fh = open(File, "r")
         except IOError, message:
            self._error(message)
         else:
            for line in fh.readlines():
               self._telnet.write(line)

            fh.close()
            self._str.write(self._telnet.read_all())
